﻿using NAudio.Wave;
using System.Windows;
using SpeedRecognition.RecordModel;

namespace SpeedRecognition
{
    internal class NaudioRecordManager
    {
        IWaveIn? _wavIn;

        public WaveFormat WaveFormat { get; } = new(16000, 1);

        public IRecordStream? RecordStream { get; set; }

        public bool IsStart { get; set; }

        /// <summary>
        /// 麦克风
        /// </summary>
        public void SetMicrophoneDevice()
        {
            _wavIn = new WaveInEvent();
            _wavIn.WaveFormat = WaveFormat;
        }

        /// <summary>
        /// 扬声器
        /// </summary>
        public void SetLoudSpeakerDevice()
        {
            _wavIn = new WasapiLoopbackCapture();
            _wavIn.WaveFormat = WaveFormat;
        }

       
        public void StartRecordAudio()
        {
            try
            {
                if (RecordStream == null)
                {
                    MessageBox.Show("请先设置存储介质!");
                    return;
                }
                if (_wavIn != null)
                {
                    _wavIn.DataAvailable += (_, a) => { RecordStream.Write(a); };

                    _wavIn.RecordingStopped += (_, _) =>
                    {
                        if (_wavIn != null)
                        {
                            _wavIn.Dispose();
                            _wavIn = null;
                        }
                        RecordStream.Dispose();
                    };

                    _wavIn.StartRecording();
                    IsStart = true;
                } 
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void StopRecordAudio()
        {
            if (_wavIn != null && IsStart)
            {
                _wavIn.StopRecording();

                _wavIn.Dispose();
                _wavIn = null;
                IsStart = false;
            }
        }
    }
}
